package m.jclecai.com.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.squareup.okhttp.Request;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import m.jclecai.com.R;
import m.jclecai.com.base.BaseActivity;
import m.jclecai.com.bean.RegisterBean;
import m.jclecai.com.bean.UserBean;
import m.jclecai.com.constant.Constant_Result;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.utils.BaseUtils;
import m.jclecai.com.utils.ChannelUtil;
import m.jclecai.com.utils.MD5;
import m.jclecai.com.utils.MyToast;
import m.jclecai.com.utils.PreferenceUtil;
import m.jclecai.com.utils.http.FastOk;
import m.jclecai.com.utils.http.HttpManager;
import m.jclecai.com.utils.http.SystemUtils;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;


/**
 * Created by hp on 2017/3/15.
 *   登录
 */

public class LoginActivity extends BaseActivity {
    @BindView(R.id.et_phone)
    EditText et_phone;
    @BindView(R.id.et_password)
    EditText et_password;
    @BindView(R.id.ll_login)
    LinearLayout ll_login;
    @BindView(R.id.tv_forget_pas)
    TextView tv_forgetPas;
    @BindView(R.id.tv_proof)
    TextView tv_proof;
    @BindView(R.id.iv_clear_phone)
    ImageView iv_clear_phone;
    @BindView(R.id.iv_clear_password)
    ImageView iv_clear_password;
    @BindView(R.id.text_bottom)
    TextView text_bottom;

    private String et_phone_text;


    @Override
    public int getContentView() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        setTitle("登录");
        rightOptionText("注册");
        leftOptionText("");
    }

    @Override
    public void initData() {
        et_phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                et_password.setText(null);
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString())) {
                    iv_clear_phone.setVisibility(View.GONE);
                } else {
                    iv_clear_phone.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant_Result.NEEDLOGIN && resultCode == RESULT_OK) {
            setResult(RESULT_OK);
            finish();
        }

        if (requestCode==Constant_Result.REQUEST_BIND_PHONE_NUMBER) {
            if(resultCode == RESULT_OK){

                if (data != null) {
                    String user = data.getStringExtra("user");
                    String password = data.getStringExtra("password");
                    HashMap<String, String> map = new HashMap<>();
                    map.put("user",user);
                    map.put("password",password);
                    loadUserInfo(map);

                }else{
                    loadUserInfo(threeLoginPairmsMap);
                }

            }
        }

        if(requestCode==Constant_Result.CLOSEPAGE){

            if(resultCode != RESULT_OK){
                //这里表示的一个操作就是；
                //使用微信的那个的那个账号登陆
                //这里我们在这里写一个标志来记录是微信登陆的；
                loadUserInfo(threeLoginPairmsMap);
            }
        }

    }

    @OnClick({R.id.ll_login, R.id.tv_forget_pas, R.id.tv_proof, R.id.tv_right_option,
            R.id.iv_clear_password, R.id.iv_clear_phone})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_login:
                //登录
                if (!BaseUtils.netWork(LoginActivity.this)) {
                    MyToast.showToast(LoginActivity.this, "请检查你的网络");
                } else {
                    logIn();
                }
                break;
            case R.id.tv_forget_pas:
                //忘记密码
                startActivityForResult(new Intent(this, NewlyResetPassWordActivity.class), Constant_Result.NEEDLOGIN);
                break;
            case R.id.tv_proof:
                //短信验证
                startActivityForResult(new Intent(this, ProofActivity.class), Constant_Result.NEEDLOGIN);
                break;
            case R.id.tv_right_option:
                //注册
                startActivity(new Intent(this, NewlyRegisterActivity.class));
                finish();
                break;
            case R.id.iv_clear_phone:
                //清除手机号码
                et_phone.setText(null);
                break;
            case R.id.iv_clear_password:
                //显示明文或密文密码
                if (et_password.getInputType() == InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD) {//可见
                    iv_clear_password.setImageResource(R.drawable.e8);
                    et_password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);
                } else {//不可见
                    iv_clear_password.setImageResource(R.drawable.e9);
                    et_password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                }
                et_password.setSelection(et_password.getText().toString().length());
                break;
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            overridePendingTransition(R.anim.activity_right_out, R.anim.activity_left_in);
            return true;
        }
        // 拦截MENU按钮点击事件，让他无任何操作
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    private void logIn() {
        //收起软键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
        }
        et_phone_text = this.et_phone.getText().toString().trim();
        String et_password = this.et_password.getText().toString().trim();


        if (TextUtils.isEmpty(et_phone_text) || TextUtils.isEmpty(et_password)) {
            MyToast.showToast(this, "请输入用户名或密码");
            return;
        }
        showDialog();
        //登录
        final String userPass = MD5.getMD5(et_password);
        final Map<String, String> pair = new HashMap<>();
        pair.put("user", et_phone_text);
        pair.put("password", userPass);
        pair.put("version", SystemUtils.getCurrentVersionCode(this));
        pair.put("channel", "android_"+ Build.VERSION.RELEASE+"_"+Build.MODEL);
        //
        HttpManager.postAsyn(Constant_Url.LOGIN_URL, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                //失败
                DisPlay("无法连接服务器");
                dissDialog();
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                //登陆成功
                RegisterBean registerBean = FastOk.get(response, RegisterBean.class);
                if (registerBean != null) {
                    String message = registerBean.getMessage();
                    MyToast.showToast(LoginActivity.this, message);
                    if (message.contains("登录成功")) {
                        loadUserInfo(pair);
                    }
                } else {
                    DisPlay(getString(R.string.error_network));
                }
            }
        }, pair);
    }

    //登录后需要加载用户信息
    protected void loadUserInfo(final Map<String, String> pair) {
        showDialog();
        HttpManager.postAsyn(Constant_Url.GET_USER_INFO, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                dissDialog();
            }

            @Override
            public void onResponse(String response) {
                dissDialog();
                UserBean userBean = FastOk.get(response, UserBean.class);
                if (userBean != null) {
                    if ("1011".equals(userBean.getStatus())) {
                        MyToast.showToast(LoginActivity.this, "获取用户信息失败！");
                        PreferenceUtil.writeUser(LoginActivity.this, null);
                    } else {
                        PreferenceUtil.setAccount(LoginActivity.this, userBean.getPhone());
                        PreferenceUtil.setUserName(LoginActivity.this, userBean.getUsername());
                        PreferenceUtil.setPassword(LoginActivity.this, pair.get("password"));
                        PreferenceUtil.setLoginStatus(LoginActivity.this, true);
                        PreferenceUtil.writeUser(LoginActivity.this, userBean);

                        //这里我们判断username是否是一个空，
                        // 如果是的话，我们就认为其没有重新设置用户名和密码的；
                        JSONObject jsonObject = JSON.parseObject(response);
                        String username = jsonObject.getString("username");
                        if(TextUtils.isEmpty(username)){
                            PreferenceUtil.writeBoolean(LoginActivity.this,PreferenceUtil.IS_USER_NAME_EMPTY,true);
                        }else{
                            PreferenceUtil.writeBoolean(LoginActivity.this,PreferenceUtil.IS_USER_NAME_EMPTY,false);
                        }

                        setResult(RESULT_OK);
                        LoginActivity.this.finish();
                    }
                } else {
                    DisPlay(getString(R.string.error_network));
                }
            }
        }, pair);
    }

    @OnClick(R.id.iv_wechat_login)
    void wechatLogin() {
        auth(Wechat.NAME);
    }

    void auth(String name) {
        showDialog();
        Platform platform = ShareSDK.getPlatform(name);
        platform.setPlatformActionListener(new MyPlatformActionListener(name));
        platform.SSOSetting(false);
        platform.showUser(null);
    }

    class MyPlatformActionListener implements PlatformActionListener {

        String mName;

        public MyPlatformActionListener(String mName) {
            this.mName = mName;
        }

        @Override
        public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
            dissDialog();
            Log.e("info", JSON.toJSONString(hashMap));
            final PlatformDb db = platform.getDb();
            System.out.println("从微信哪里获取的数据为："+platform.getDb().exportData());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                  //  threePartLogin(db.get("nickname"),db.get("unionid"),db.getUserIcon());

                    HashMap<String, String> map = new HashMap<>();
                    map.put("nickname", db.get("nickname"));
                    map.put("unionid", db.get("unionid"));
                    map.put("flag",db.getUserIcon());
                    map.put("channel", "android_"+ Build.VERSION.RELEASE+"_"+Build.MODEL);
                    map.put("appstore", ChannelUtil.getChannel());
                    threePartLogin(map);
                }
            });
        }

        @Override
        public void onError(Platform platform, int i, Throwable throwable) {
            DisPlay(throwable.getMessage());
            dissDialog();
        }

        @Override
        public void onCancel(Platform platform, int i) {
            DisPlay("cancel");
            dissDialog();
        }
    }

    Map<String, String> threeLoginPairmsMap;

    void threePartLogin(final HashMap<String,String> hashMap) {

        Observable.just(true)
                .map(new Func1<Boolean, UserBean>() {
            @Override
            public UserBean call(Boolean aBoolean) {
                //三方的登陆
                return threeLogin(hashMap);
            }
        }).map(new Func1<UserBean, UserBean>() {
            @Override
            public UserBean call(UserBean userBean) {
                //getUserBindInfo
                if("0".equals(userBean.getStatus())){
                    //这里我们要判断一下绑定手机号没有，如果没有就去绑定；
                    //这里我们就需要跳转到到绑定手机号的activity;
                    threeLoginPairmsMap = new HashMap<>();
                    threeLoginPairmsMap.put("user",userBean.getUsername());
                    threeLoginPairmsMap.put("password",userBean.getPassword()); //这里我们可以获取一个密码，要么是微信的登陆密码，要么是用户名的密码；

                    if (!"0".equals(userBean.getPhonenumberid())) {
                        //getUserInfo里面是没有密码的；
                        UserBean user = getUserInfo(threeLoginPairmsMap);
                        user.setPassword(userBean.getPassword());
                        return user;
                    }
                }else{
                    throw new RuntimeException(userBean.getMessage());
                }
                return userBean;
            }
        }).subscribeOn(Schedulers.io())
        .unsubscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Subscriber<UserBean>() {

            UserBean mUserBean;

            @Override
            public void onStart() {
                super.onStart();
                showDialog();
            }

            @Override
            public void onCompleted() {
                //这里我们判断是否登陆或者跳转到相应的界面；
                dissDialog();
                if(mUserBean!=null){
                    if ("0".equals(mUserBean.getPhonenumberid())) {
                        DisPlay("未绑定手机号！！！");

                        Bundle data = new Bundle();
                        data.putString("user",mUserBean.getUsername());
                        data.putString("password",mUserBean.getPassword());
                        //绑定手机号
                        Intent intent = RegisterActivity.getIntent(LoginActivity.this,true,true,data);
                        HashMap<String, String> map = new HashMap<>();
                        map.put("user",mUserBean.getUsername());
                        map.put("password",mUserBean.getPassword());
                        intent.putExtra("param",JSON.toJSONString(map));
                        intent.putExtra("from","2");

                        PreferenceUtil.writeBoolean(LoginActivity.this,PreferenceUtil.WEI_XIN_IS_BIND_PHONE_NUMBER,false);

                        startActivityForResult(intent, Constant_Result.REQUEST_BIND_PHONE_NUMBER);

                    } else if (mUserBean.isUserNameEmpty()) {
                        //设置用户名和密码；
                        DisPlay("未设置用户名！！！");
                        Intent intent = RegisterActivity.getIntent(LoginActivity.this,false);
                        intent.putExtra("param",JSON.toJSONString(threeLoginPairmsMap));
                        startActivityForResult(intent, Constant_Result.CLOSEPAGE);
                    }else{
                        //登陆
                        logIn(mUserBean.getUsername(), mUserBean.getPassword(), false, new m.jclecai.com.listener.Callback() {
                            @Override
                            public void callbackSuccess() {
                                super.callbackSuccess();
                                setResult(Activity.RESULT_OK);
                                finish();
                            }

                            @Override
                            public void callbackField() {
                                super.callbackField();
                                DisPlay("请检查网络！！！");
                            }
                        });

                    }
                }
            }

            @Override
            public void onError(Throwable e) {
                dissDialog();
                if (e instanceof RuntimeException) {
                    DisPlay(e.getMessage());
                }
                e.printStackTrace();
            }

            @Override
            public void onNext(UserBean userBean) {
                this.mUserBean=userBean;
            }
        });
    }

    private UserBean getUserInfo(Map<String, String> map) {

        UserBean userBean = null;
        try {
            String responseBody = HttpManager.postAsString(Constant_Url.GET_USER_INFO, map);
            userBean = FastOk.get(responseBody, UserBean.class);

            JSONObject jsonObject = JSON.parseObject(responseBody);
            String username = jsonObject.getString("username");
            userBean.setUserNameEmpty(TextUtils.isEmpty(username));

        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("网络异常");
        }
        return userBean;
    }

    private UserBean threeLogin(HashMap<String, String> hashMap) {

        UserBean userBean = null;
        try {
            String responseBody = HttpManager.postAsString(Constant_Url.WEIXIN_LOGIN, hashMap);
            userBean = FastOk.get(responseBody, UserBean.class);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("网络异常");
        }
        return userBean;
    }
}
